package com.luoying.itew.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProviders;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.TextOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.luoying.itew.R;
import com.luoying.itew.activity.DistrictMapActivity;
import com.luoying.itew.activity.InformationActivity;
import com.luoying.itew.activity.MainActivity;
import com.luoying.itew.activity.MainActivityViewModel;
import com.luoying.itew.bean.DistrictBean;
import com.luoying.itew.bean.MonitorBean;
import com.luoying.itew.bean.StreetBean;
import com.luoying.itew.common.Constant;
import com.luoying.itew.dialog.PointsListDialog;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.AppUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.luoying.itew.fragment.InspectLogFragment.TAG;

/**
 * Created by lufan on 2019-04-23
 * Class describe
 */
public class MapFragment extends BaseFragment implements AMap.OnMarkerClickListener, View.OnClickListener {

    @BindView(R.id.map_view)
    MapView mapView;
    @BindView(R.id.home_map_note)
    TextView mapNoteTv;
    @BindView(R.id.home_map_layer)
    ImageView layerImage;

    /**
     * ViewModel
     */
    private MainActivityViewModel mModel;
    /**
     * 地图控制类
     */
    private AMap aMap;

    Disposable disposable;
    //是否是公司用户
    boolean isCompanyUser = false;


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_map;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        aMap.setOnMarkerClickListener(this::onMarkerClick);
        isCompanyUser = UserManage.getInstance().getUserInfo().getUserType() == 3 ;
    }

    @Override
    protected void init() {
        super.init();
        mModel = ViewModelProviders.of(getActivity()).get(MainActivityViewModel.class);
        mModel.getAllStree().observe(this, streetBeans -> {
            isCompanyUser = UserManage.getInstance().getUserInfo().getUserType() == 3 ;
            Log.d(TAG, "init: is gov user "+ isCompanyUser);
            drawInfoOverlay(streetBeans);
            showNoteTextView();
        });
        //请求数据
        mModel.getUserAndMapInfo();
        mModel.updateVersion();
        mapNoteTv.setOnClickListener(this::onClick);
        layerImage.setOnClickListener(this::onClick);
        //搜索深圳市绘制深圳市区域
        searchCity("深圳市");
        searchCity("海丰县");
        searchCity("梅州市");
    }

    /**
     * 绘制观察点
     */
    public void drawInfoOverlay(List<StreetBean> list) {
        //地图的缩放级别一共分为 17 级，从 3 到 19。数字越大，展示的图面信息越精细。
        //直接移动深圳市
        LatLng cenpt = null;
        if(list.size()==1&&list.get(0).getRegionAreaId()==90){
            //梅州特殊处理
            cenpt = new LatLng(24.299112,116.117582);
        } else {
            cenpt = new LatLng(22.984975,114.720079);
        }

        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(cenpt,9));
        //所有区级列表
        List<StreetBean> streetList = new ArrayList<>();
        if(isCompanyUser){
            for (MonitorBean monitorBean : UserManage.getInstance().getAllMonitorList()) {
                for (StreetBean streetBean : list) {
                    if(streetBean.getRegionAreaId()==monitorBean.getMonitorArea().getParentAreaId()){
                        streetList.add(streetBean);
                    }
                }
            }
        } else {
            for (StreetBean streetBean : list) {
                if (streetBean.getAreaLevel() == 2) {
                    streetList.add(streetBean);
                }
            }
        }

        //地图转换
        Observable<BitmapDescriptor> observableMap = Observable.fromIterable(streetList)
                .flatMap(new Function<StreetBean, ObservableSource<Integer>>() {
                    @Override
                    public ObservableSource<Integer> apply(@io.reactivex.annotations.NonNull StreetBean streetBean) throws Exception {
                        if(isCompanyUser &&streetBean.getAreaLevel() == 2 ){
                            return Observable.just(-1000);
                        } else {
                            return  Observable.just(UserManage.getInstance().getAreaState(streetBean.getRegionAreaId()));
                        }
                    }
                })
                .observeOn(Schedulers.io())
                .map(integer -> {
                    BitmapDescriptor bitmap;
                    switch (integer) {
                        default:
                        case Constant.WARN_LEVEL_GREEN:
                            bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_stree);
                            break;
                        case Constant.WARN_LEVEL_YELLOW:
                            bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_stree_yu);
                            break;
                        case Constant.WARN_LEVEL_ORANGE:
                            bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_stree_orange);
                            break;
                        case Constant.WARN_LEVEL_RED:
                            bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_stree_error);
                            break;
//                        case -1000:
//                            bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_government);
//                            break;
                    }
                    return bitmap;
                });

        //MarkerOptions 转换
        Observable<MarkerOptions> observableMarker =Observable.fromIterable(streetList)
                .observeOn(Schedulers.io())
                .map(streetBean -> {
                    LatLng latLng = new LatLng(Double.parseDouble(streetBean.getRegionLat()),
                            Double.parseDouble(streetBean.getRegionLng()));
                    TextOptions textOptions = new TextOptions()
                            .position(latLng)
//                            .text(streetBean.getRegionName())
                            .text(streetBean.getRegionName().equals("海丰县")?"深汕合作新区":streetBean.getRegionName())
                            .fontSize(AppUtils.sp2px(12))
                            .fontColor(Color.DKGRAY);
                    aMap.addText(textOptions);
                    return new MarkerOptions()
                            .position(latLng)
                            .draggable(false);
                });

        //压缩地图和MarkerOptions压缩
        disposable = Observable.zip(observableMap, observableMarker, (bitmapDescriptor, markerOptions) -> markerOptions.icon(bitmapDescriptor))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(markerOptions ->aMap.addMarker(markerOptions));
    }

    /**
     * 搜索城市信息
     * @param searchCity  搜索的城市名称
     */
    public void searchCity(String searchCity) {
        DistrictSearchQuery query = new DistrictSearchQuery();
        //传入关键字
        query.setKeywords(searchCity);
        //是否返回边界值
        query.setShowBoundary(true);
        DistrictSearch districtSearch = new DistrictSearch(getContext());
        //设置搜索条件
        districtSearch.setQuery(query);
        districtSearch.setOnDistrictSearchListener(districtResult -> {
            if (districtResult.getAMapException().getErrorCode() != AMapException.CODE_AMAP_SUCCESS) {
                return;
            }
            for (int i = 0; i < districtResult.getDistrict().size(); i++) {
                DistrictItem item = districtResult.getDistrict().get(i);
                String[] polyStr = item.districtBoundary();
                if (polyStr == null || polyStr.length == 0) {
                    return;
                }
                for (String str : polyStr) {
                    String[] lat = str.split(";");
                    PolygonOptions polylineOption = new PolygonOptions();
                    boolean isFirst = true;
                    LatLng firstLatLng = null;
                    for (String latstr : lat) {
                        String[] lats = latstr.split(",");
                        if (isFirst) {
                            isFirst = false;
                            firstLatLng = new LatLng(Double.parseDouble(lats[1]), Double.parseDouble(lats[0]));
                        }
                        polylineOption.add(new LatLng(Double.parseDouble(lats[1]), Double.parseDouble(lats[0])));
                    }
                    if (firstLatLng != null) {
                        polylineOption.add(firstLatLng);
                    }
                    polylineOption.strokeWidth(6)
                            .strokeColor(Color.parseColor("#FF136014"))
                            .fillColor(Color.argb(100, 128, 216, 255));
                    aMap.addPolygon(polylineOption);
                }
            }
        });
        //开始搜索
        districtSearch.searchDistrictAsyn();
    }

    /**
     * 展示待办列表文案
     */
    private void showNoteTextView(){
        //红色级别监测点集合
        List<MonitorBean> redList = UserManage.getInstance().getRedLevelMontor();
        //黄色级别监测点集合
        List<MonitorBean> yellowList = UserManage.getInstance().getYellowMontors();
        //橙色级别监测点集合
        List<MonitorBean> orangeList = UserManage.getInstance().getOrangeMontors();
        if(redList.isEmpty()&&yellowList.isEmpty()&&orangeList.isEmpty()){
            mapNoteTv.setVisibility(View.GONE);
            return;
        }
        mapNoteTv.setVisibility(View.VISIBLE);
        StringBuilder stringBuilder = new StringBuilder("您管辖的区域有");

        if(!redList.isEmpty()){
            stringBuilder
                    .append(redList.size())
                    .append("个监测点达到红色报警级别");
        }

        if(!orangeList.isEmpty()){
            if(!redList.isEmpty()){
                stringBuilder.append(";");
            }
            stringBuilder
                    .append(orangeList.size())
                    .append("个监测点达到橙色预警级别");
        }

        if(!yellowList.isEmpty()){
            if(!redList.isEmpty()){
                stringBuilder.append(";");
            }
            stringBuilder
                    .append(yellowList.size())
                    .append("个监测点达到黄色预警级别");
        }
        stringBuilder.append(",点击查看监测点列表");
        stringBuilder.append("                         ");
        mapNoteTv.setText(stringBuilder.toString());
        mapNoteTv.postDelayed(() -> mapNoteTv.setSelected(true),500);
    }

    private void govUserClick(StreetBean streetBean){
        List<MonitorBean> list = UserManage.getInstance().getListMonitorFromStreeId(streetBean);
//        if(streetBean.getAreaLevel() == 2){
//            Toast.makeText(getContext(), streetBean.getRegionName(), Toast.LENGTH_LONG).show();
//            return;
//        }
        if (list.size() > 0) {
            PointsListDialog dialog = new PointsListDialog(getContext(), list);
            dialog.show();
            dialog.setListener((bean) -> {
                //查看详情
                Intent intent = new Intent(getContext(), InformationActivity.class);
                intent.putExtra("cuurMonitorId", bean.getMonitorPointId());
                startActivity(intent);
//                if (mMarkerInfoLy != null) {
//                    mMarkerInfoLy.setVisibility(View.GONE);
//                }
            });
        } else {

            Toast.makeText(getContext(), "没有监测点", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 点击街道办后dialog提示
     */
    private void markClickDialog(StreetBean streetBean){
        if(streetBean==null){
            return;
        }

        int id = streetBean.getRegionAreaId();
        DistrictBean bean = UserManage.getInstance().getDistricById(id);
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        if (bean == null) {
            String regionName = streetBean.getRegionName();
            builder.setMessage("查看"+regionName.substring(0,regionName.length()-2) + "(无监测点)");
        } else {
            builder.setMessage("查看" + bean.getDistrict().getAreaName() + "监测点");
        }
        builder.setNegativeButton("取消",null);
        builder.setPositiveButton("查看", (dialog, which) -> {
            Intent intent = new Intent(getContext(), DistrictMapActivity.class);
            intent.putExtra("districtId", id);
            intent.putExtra("map_type", aMap==null?AMap.MAP_TYPE_NORMAL:aMap.getMapType());
            startActivity(intent);
        });
        builder.show();
    }



    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mapView!=null){
            mapView.onDestroy();
        }
        if(disposable!=null){
            disposable.dispose();
        }
    }

    /**
     * 绘制物（旗子）的点击事件
     * @param marker
     * @return
     */
    @Override
    public boolean onMarkerClick(Marker marker) {
        StreetBean bean = null;
        if(aMap!=null){
            List<StreetBean> allStreetList = UserManage.getInstance().getAllStreetList();
            LatLng latLng = marker.getPosition();
//            aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
            for (StreetBean streetBean : allStreetList) {
                if(String.valueOf(latLng.latitude).equals(streetBean.getRegionLat())&&
                        String.valueOf(latLng.longitude).equals(streetBean.getRegionLng())){
                    bean = streetBean;
                    break;
                }
            }

            if(bean!=null){
                if(isCompanyUser){
                    govUserClick(bean);
                } else {
                    //街道办点击事件
                    markClickDialog(bean);
                }
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.home_map_note){
            ((MainActivity)getActivity()).switcTab(MainActivity.TYPE_LIST);
        }
        if(v.getId()==R.id.home_map_layer){
            if(aMap==null){
                return;
            }
            //地图图层切换
            aMap.setMapType(aMap.getMapType()==AMap.MAP_TYPE_NORMAL?AMap.MAP_TYPE_SATELLITE:AMap.MAP_TYPE_NORMAL);
        }

    }
}
